package com.suozq.springcloud.payment.buss.payment.controller;

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;


@RestController
public class PaymentController {
	
	@Autowired
	DiscoveryClient discoveryClient;
	
	@Value("${server.port}")
	String port;
	
	@GetMapping("/test/{id}") 
	@HystrixCommand(fallbackMethod = "testFallback",commandProperties ={
        @HystrixProperty(name = "circuitBreaker.enabled",value = "true"), //开启熔断器
        @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds",value ="10000"), //统计时间窗
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),      //统计时间窗内请求次数
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), //休眠时间窗口期
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"), //在统计时间窗口期以内，请求失败率达到 60% 时进入熔断状态
    })
	public String test(@PathVariable Integer id) {
		try {
			TimeUnit.SECONDS.sleep(3);
			id = id>0?id:id/0;
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return port;
	}
	
	public String testFallback(Integer id) {
		return "breakFallBack";
	}
	
	@GetMapping("/dis")
	public Object getDiscoveryClient() {
		return discoveryClient;
	}
}
